package com.cube.dp.cor.filter;

import com.cube.dp.base.utils.ResponseUtils;
import com.cube.dp.cor.context.TransformContext;
import com.cube.dp.cor.context.TransformStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author cube.li
 * @date 2021/12/13 21:44
 * <p>
 * 短信转换重定向过滤器,在短链转长链完成后进行重定向
 */
@Component
@Slf4j
public class RedirectTransformFilter implements TransformFilter {

    @Override
    public void doFilter(TransformContext context) {
        log.debug("短链转换-重定向...");
        try {
            HttpServletResponse response = ResponseUtils.currentResponse();
            //noinspection ConstantConditions
            redirect302(response, context.getOriginLongUrl());
            context.setTransformStatus(TransformStatus.REDIRECTION_SUCCESS);
        } catch (Exception e) {
            context.setTransformStatus(TransformStatus.REDIRECTION_FAIL);
        }

    }

    /**
     * 永久重定向,由于浏览器重定向缓存无法记录到所有的短链转换行为
     *
     * @param response      响应
     * @param originLongUrl 原始链接
     */
    private void redirect301(HttpServletResponse response, String originLongUrl) {
        response.setStatus(301);
        response.setHeader("Location", originLongUrl);
    }

    /**
     * 临时重定向,浏览器不会缓存重定向信息会记录到每次点击
     *
     * @param response      响应
     * @param originLongUrl 原始链接
     */
    private void redirect302(HttpServletResponse response, String originLongUrl) throws IOException {
        response.setStatus(302);
        response.sendRedirect(originLongUrl);
    }

    @Override
    public int getOrder() {
        return 2;
    }
}
